package activitys;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import mytool.Distance;
import mytool.GaussXYDeal;
import mytool.Gps2BaiDu;
import mytool.HttpSend;
import mytool.Itude;
import mytool.JsonParser;
import mytool.ListTools;
import mytool.PrintLog;
import mytool.ShardPreferencesTool;
import mytool.ToastShow;
import tool.ducong.com.mygpsdemo.MyAPP;
import tool.ducong.com.mygpsdemo.R;

/**
 * Created by zerdoor_pc on 2016/3/3.
 */
public class Base_stationActivity extends Activity {
    private TextView jizhan,accuracy,flag_now, station_number, base_revised_longitude, base_revised_latitude, base_longitude, base_latitude, base_differential_x, base_differential_y;
    private EditText number_edit, base_longitude_edit, base_latitude_edit;
    private Button base_edit, base_preservation, base_cancel;
    private double longitude, latitude;
    private Itude mitude;
    private int isSendHttp = 0;
    private Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //PrintLog.i("HTTPURL:url=" + msg.obj);
            switch (msg.what) {
                case 0:
                    PrintLog.i("HTTPURL:" + "接收hander");
                    if (isSendHttp != 1) {
                        //PrintLog.i("HTTPURL:" + "初始化更新");
                        setdifferential();
                    }
                    break;
                case 2:
                    PrintLog.i("2==" + msg.obj);
                    if (JsonParser.CheckCode((String) msg.obj)) {
//                    Toast.makeText(Base_stationActivity.this,"基站差分值提交成功！",Toast.LENGTH_SHORT).show();
                        flag_now.append("\n基站差分信息第"+updatetimes+++"次同步成功!");
                        updatesuccesstimes++;
                        hander.sendEmptyMessage(4);
                    } else {
                        flag_now.append("\n基站差分信息第"+updatetimes+++"次同步失败!");
                        ToastShow.showShort(Base_stationActivity.this, "" + msg.obj);
                    }
                    break;
                case 3:
                    PrintLog.i("1==" + msg.obj);
                    if (JsonParser.CheckCode((String) msg.obj)) {
//                        Toast.makeText(Base_stationActivity.this,"基站经纬度提交成功！",Toast.LENGTH_SHORT).show();
                        flag_now.append("\n基站经纬度同步成功!");
                        HttpSend.UploadDifferenceData(hander, 2, station_number.getText().toString(), MyAPP.differentialitude.getLatitude() + "", MyAPP.differentialitude.getLongitude() + "");

                    } else {
                        flag_now.append("\n基站经纬度同步失败!");
                        ToastShow.showShort(Base_stationActivity.this, "" + msg.obj);

                    }
                    break;
                case 4:
                    flag_now.append("\n基站信息同步成功!");
                    jizhan.setText(R.string.base_station_data);
                    jizhan.append(":已同步成功"+updatesuccesstimes+"次");
                    time = 0;
                    break;
                default:
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.basestationactivity_item);
        findView();
        inItDate();
    }

    private void findView() {
        station_number = (TextView) findViewById(R.id.base_station_number);
        jizhan = (TextView) findViewById(R.id.jizhan);
        accuracy = (TextView) findViewById(R.id.accuracy);
        //实际经纬
        base_revised_longitude = (TextView) findViewById(R.id.base_revised_longitude);
        base_revised_latitude = (TextView) findViewById(R.id.base_revised_latitude);
        //实时经纬
        base_longitude = (TextView) findViewById(R.id.base_longitude);
        base_latitude = (TextView) findViewById(R.id.base_latitude);
        //差分值
        base_differential_x = (TextView) findViewById(R.id.base_differential_x);
        base_differential_y = (TextView) findViewById(R.id.base_differential_y);
        flag_now = (TextView) findViewById(R.id.flag_now);

        number_edit = (EditText) findViewById(R.id.base_station_number_edit);
        base_longitude_edit = (EditText) findViewById(R.id.base_longitude_edit);
        base_latitude_edit = (EditText) findViewById(R.id.base_latitude_edit);

        base_edit = (Button) findViewById(R.id.base_edit);
        base_preservation = (Button) findViewById(R.id.base_preservation);
        base_cancel = (Button) findViewById(R.id.base_cancel);
//        longitude=104.058093;
//        latitude=30.570454;

        MyAPP.Basehandler = hander;
        station_number.setText(ShardPreferencesTool.getshare(this, "station_number", UUID.randomUUID() + ""));
        longitude = Double.parseDouble(ShardPreferencesTool.getshare(this, "longitude", "104.05860551388889"));
        latitude = Double.parseDouble(ShardPreferencesTool.getshare(this, "latitude", "30.570495625"));
        hander.postDelayed(runnable, 1000);

    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            time += 1;
            if (time % 12 == 0) {
                if (time % 120 == 0) {

                    isUpdate = true;
                }
                hander.sendEmptyMessage(0);
            }
            hander.postDelayed(runnable, 1000);
        }
    };

    private void inItDate() {
        setdifferential();
    }

    List<Itude> MyItude2;
    private List<Itude> MyItude = new ArrayList<>();

    public void setdifferential() {

        base_revised_longitude.setText(longitude + "");
        base_revised_latitude.setText(latitude + "");
        // flag_now.setText("正在获取基站经纬度");
        mitude = GaussXYDeal.GaussToBLToGauss(longitude, latitude);
        base_longitude.setText(R.string.longitude);
        base_latitude.setText(R.string.latitude);
        if (MyAPP.itude != null) {
            base_longitude.append(MyAPP.itude.getLongitude() + "");
            base_latitude.append(MyAPP.itude.getLatitude() + "");
            // flag_now.setText("正在获取基站实时GPS经纬度");
            //设置差分值并显示
            Itude itude = GaussXYDeal.GaussToBLToGauss(MyAPP.itude.getLongitude(), MyAPP.itude.getLatitude());
            flag_now.setText("正在采集差分信息"+time);
            MyAPP.differentialitude = new Itude();
            MyAPP.differentialitude.setLongitude(itude.getLongitude() - mitude.getLongitude());
            MyAPP.differentialitude.setLatitude(itude.getLatitude() - mitude.getLatitude());
            base_differential_x.setText(R.string.x);
            base_differential_y.setText(R.string.y);
            base_differential_x.append("" + MyAPP.differentialitude.getLatitude());
            base_differential_y.append("" + MyAPP.differentialitude.getLongitude());

           // double[] OLDitude  =GaussXYDeal.GaussToBL(itude.getLatitude()-MyAPP.differentialitude.getLatitude(),itude.getLongitude()-MyAPP.differentialitude.getLongitude());

            //flag_now.append("\n"+OLDitude[1]+"==="+OLDitude[0]);
            MyItude.add(MyAPP.differentialitude);
            MyItude2 = null;
            MyItude2 = ListTools.check(MyItude, 10);

            PrintLog.i("HTTPURL:" + "初始化成功isSendHttp=" + isSendHttp + "  time=" + time);
            if (isSendHttp == 0 || isSendHttp == 1) {
                isSendHttp = 0;
                if (isUpdate) {
                    MyAPP.differentialitude = ListTools.getItude(MyItude2);
                    flag_now.append("\n 平均x:" + MyAPP.differentialitude.getLatitude() + "  y:" + MyAPP.differentialitude.getLongitude());
                    isUpdate = false;
                    PrintLog.i("HTTPURL:" + "正在同步基站信息");
                  //  MyAPP.differentialitude = ListTools.getItude(MyItude2);
                    double[] OLDitude  =GaussXYDeal.GaussToBL(itude.getLatitude()-MyAPP.differentialitude.getLatitude(),itude.getLongitude()-MyAPP.differentialitude.getLongitude());
                    accuracy.setText("定位精度:"+ Distance.getDisance(OLDitude[1],OLDitude[0], 30.570495625, 104.05860551388889)+"米");
                    flag_now.append("\n正在同步基站信息!");
                    HttpSend.UpdateBaseStationInfo(hander, 3, station_number.getText().toString(), base_revised_longitude.getText().toString(), base_revised_latitude.getText().toString());
                }


            }
        }

    }

    int time = 0;
    int updatetimes=1;
    int updatesuccesstimes=0;
    Boolean isUpdate = true;

    public void edit(View v) {
        if (v == base_edit) {
            base_edit.setVisibility(View.GONE);
            station_number.setVisibility(View.GONE);
            base_revised_longitude.setVisibility(View.GONE);
            base_revised_latitude.setVisibility(View.GONE);
            number_edit.setText(station_number.getText());
            base_longitude_edit.setText(base_revised_longitude.getText());
            base_latitude_edit.setText(base_revised_latitude.getText());
            base_preservation.setVisibility(View.VISIBLE);
            base_cancel.setVisibility(View.VISIBLE);
            number_edit.setVisibility(View.VISIBLE);
            base_longitude_edit.setVisibility(View.VISIBLE);
            base_latitude_edit.setVisibility(View.VISIBLE);
            isSendHttp = 1;
        } else if (v == base_preservation) {
            String numberedit = String.valueOf(number_edit.getText());
            String longitude_edit = String.valueOf(base_longitude_edit.getText());
            String latitude_edit = String.valueOf(base_latitude_edit.getText());
            if (numberedit.length() != 0 && longitude_edit.length() != 0 && latitude_edit.length() != 0) {
                try {
                    station_number.setText(numberedit);
                    longitude = Double.parseDouble(longitude_edit);
                    latitude = Double.parseDouble(latitude_edit);
                    ShardPreferencesTool.saveshare(this, "station_number", numberedit);
                    ShardPreferencesTool.saveshare(this, "longitude", longitude_edit);
                    ShardPreferencesTool.saveshare(this, "latitude", latitude_edit);
                    setdifferential();
                    cancel(null);
                } catch (Exception e) {
                    ToastShow.showShort(this, "数据格式输入有误！");
                }

            } else {
                ToastShow.showShort(this, "数据不能为空！");

            }
        }
    }

    public void cancel(View v) {
        base_edit.setVisibility(View.VISIBLE);
        station_number.setVisibility(View.VISIBLE);
        base_revised_longitude.setVisibility(View.VISIBLE);
        base_revised_latitude.setVisibility(View.VISIBLE);
        base_preservation.setVisibility(View.GONE);
        base_cancel.setVisibility(View.GONE);
        number_edit.setVisibility(View.GONE);
        base_longitude_edit.setVisibility(View.GONE);
        base_latitude_edit.setVisibility(View.GONE);
        closrThisInputMethodManager();
    }

    private void closrThisInputMethodManager() {
        try {
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
        }
    }


}
